﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

namespace WebApplication1.Common
{
    /// <summary>
    /// 数据库访问封装类
    /// </summary>
    public class SQLHepler
    {
        //公司台式机
        public static string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

        /// <summary>
        /// 分页查询,top分页
        /// </summary>
        /// <param name="key">主键列名</param>
        /// <param name="orderby">排序语句</param>
        /// <param name="tableName">表名称</param>
        /// <param name="sqlWhere">查询条件,从条件开始写，比如：“ index=1 ”</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns>DataSet</returns>
        public static DataTable GetPaging(string key, string orderby, string tableName, string sqlWhere, int pageIndex, int pageSize)
        {
            StringBuilder sqlText = new StringBuilder();
            if (pageSize == 0)
            {
                pageSize = 10;
            }
            if (pageIndex == 0)
            {
                pageIndex = 1;
            }
            sqlText.Append(" select top " + pageSize + " * from " + tableName + " ");
            sqlText.Append(" where " + key + " not in (select top " + (pageIndex - 1) * pageSize + " " + key + " from " + tableName + "");
            if (string.IsNullOrEmpty(sqlWhere) == false)
            {
                sqlText.Append(" where " + sqlWhere);//从条件开始写，比如：“index=1 ”
            }
            sqlText.Append(" order by " + orderby + ") ");
            if (string.IsNullOrEmpty(sqlWhere) == false)
            {
                sqlText.Append(" and " + sqlWhere);//从条件开始写，比如：“index=1 ”
            }
            sqlText.Append(" order by " + orderby);

            SqlCommand comm = null;
            DataTable dt = null;
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connectionString);
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                comm = new SqlCommand(sqlText.ToString(), conn);
                SqlDataAdapter sda = new SqlDataAdapter(comm);
                dt = new DataTable();
                sda.Fill(dt);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                CloseDispose(null, comm, conn);
            }
            return dt;
        }

        /// <summary>
        /// 关闭对象，释放资源
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="cmd"></param>
        /// <param name="con"></param>
        protected static void CloseDispose(SqlDataReader dr, SqlCommand cmd, SqlConnection con)
        {
            if (dr != null)
            {
                dr.Close();
                dr.Dispose();
            }
            if (cmd != null)
            {
                cmd.Dispose();
            }
            if (con != null)
            {
                con.Close();
                con.Dispose();
            }
        }

        #region 外部调用

        /// <summary>
        /// 执行sql语句返回受影响的行数
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="param">参数列表</param>
        /// <returns>返回受影响的行数</returns>
        public static int ExecuteSql(string sql, params SqlParameter[] param)
        {
            SqlCommand cmd = null;
            SqlConnection conn = null;
            int count = 0;
            try
            {
                conn = new SqlConnection(connectionString);
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddRange(param);
                count = cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                CloseDispose(null, cmd, conn);
            }
            return count;
        }

        /// <summary>
        /// 执行sql语句，返回DataTable
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="param">参数列表</param>
        /// <returns>DataTable</returns>
        public static DataSet GetDataSet(string sql, params SqlParameter[] param)
        {
            SqlCommand cmd = null;
            DataSet ds = null;
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connectionString);
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddRange(param);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                ds = new DataSet();
                sda.Fill(ds);
                sda.Dispose();
                cmd.Parameters.Clear();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                CloseDispose(null, cmd, conn);
            }
            return ds;
        }

        /// <summary>
        /// 返回单值
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="param">参数，单个或数组或为空</param>
        /// <returns></returns>
        public static object GetSingleValue(string sql, params SqlParameter[] param)
        {
            object obj = null;
            SqlCommand cmd = null;
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connectionString);
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddRange(param);
                obj = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                CloseDispose(null, cmd, conn);
            }
            return obj;
        }

        /// <summary>
        /// 执行事务，返回受影响行数
        /// </summary>
        /// <param name="cmdList">参数列表，数组里面下标0为sql语句，1为SqlParameter参数</param>
        /// <returns></returns>
        public static int ExecSqlTransacation(List<object[]> cmdList)
        {
            int count = 0;
            SqlCommand cmd = null;
            SqlConnection conn = null;
            SqlTransaction tran = null;
            try
            {
                conn = new SqlConnection(connectionString);
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                tran = conn.BeginTransaction();
                foreach (object[] arr in cmdList)
                {
                    string sql = arr[0] as string; //sql语句
                    SqlParameter[] parmes = arr[1] as SqlParameter[];//参数
                    cmd = new SqlCommand(sql, conn);
                    if (parmes != null)
                    {
                        cmd.Parameters.AddRange(parmes);
                    }
                    cmd.Transaction = tran;
                    int efCount = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    count += efCount;
                }
                tran.Commit();
            }
            catch (Exception)
            {
                tran.Rollback();
                throw;
            }
            finally
            {
                CloseDispose(null, cmd, conn);
            }
            return count;
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="produreName">存储过程名称</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public static DataTable ExecStoredProcedure(string produreName, params SqlParameter[] parameters)
        {
            SqlCommand comm = null;
            DataTable dt = null;
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connectionString);
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                comm = new SqlCommand(produreName, conn);
                comm.CommandType = CommandType.StoredProcedure;//执行存储过程
                comm.Parameters.AddRange(parameters);
                SqlDataAdapter sda = new SqlDataAdapter(comm);
                dt = new DataTable();
                sda.Fill(dt);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                CloseDispose(null, comm, conn);
            }
            return dt;
        }

        #endregion


    }
}
